package com.example.furniture.service.impl;

import com.example.furniture.dto.AiChatRequest;
import com.example.furniture.dto.AiChatResponse;
import com.example.furniture.service.AiChatService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI对话服务实现
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@Service
public class AiChatServiceImpl implements AiChatService {

    private static final Logger logger = LoggerFactory.getLogger(AiChatServiceImpl.class);
    private static final String API_URL = "https://api.siliconflow.cn/v1/chat/completions";
    private static final String API_KEY = "sk-gmsplaguznbcsgawhywbfcfygizaesiyndftmszppbmnmztc";
    private static final String MODEL = "Qwen/Qwen2.5-7B-Instruct";

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public AiChatServiceImpl() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public AiChatResponse chat(AiChatRequest request) throws Exception {
        try {
            logger.info("发送AI对话请求: {}", request.getMessage());

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", MODEL);
            requestBody.put("messages", List.of(
                Map.of("role", "user", "content", request.getMessage())
            ));
            requestBody.put("max_tokens", 1000);
            requestBody.put("temperature", 0.7);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(API_KEY);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            logger.info("发送请求到: {}, 模型: {}", API_URL, MODEL);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(API_URL, entity, String.class);

            logger.info("收到响应状态: {}", response.getStatusCode());
            logger.debug("响应内容: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                // 解析响应
                JsonNode jsonResponse = objectMapper.readTree(response.getBody());
                String reply = jsonResponse.path("choices")
                        .get(0)
                        .path("message")
                        .path("content")
                        .asText();

                logger.info("AI对话成功，回复长度: {}", reply.length());
                return new AiChatResponse(reply, MODEL);
            } else {
                String errorBody = response.getBody();
                logger.error("API调用失败，状态码: {}, 响应: {}", response.getStatusCode(), errorBody);
                throw new Exception("AI服务调用失败，状态码: " + response.getStatusCode() + ", 响应: " + errorBody);
            }

        } catch (Exception e) {
            logger.error("AI对话失败", e);
            // 提供更详细的错误信息
            String errorMsg = e.getMessage();
            if (errorMsg != null && errorMsg.contains("Model does not exist")) {
                errorMsg = "模型不存在，请检查模型名称配置";
            } else if (errorMsg != null && errorMsg.contains("401")) {
                errorMsg = "API密钥无效或已过期";
            } else if (errorMsg != null && errorMsg.contains("429")) {
                errorMsg = "请求过于频繁，请稍后重试";
            }
            throw new Exception("AI对话失败: " + errorMsg);
        }
    }
}